// 使用window.onload而不是DOMContentLoaded，确保所有内容都加载完成
window.addEventListener('load', function() {
    console.log('window load 事件已触发');

    // 检查Bootstrap是否已加载
    if (typeof bootstrap === 'undefined') {
        console.error('Bootstrap 未加载');
        return;
    }

    // 获取 CSRF 令牌
    const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
    const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

    // 打印页面上所有模态框相关的元素
    console.log('页面上所有模态框元素:');
    document.querySelectorAll('.modal').forEach(modal => {
        console.log('找到模态框:', modal.id);
    });

    // 检查模态框元素是否存在并初始化
    let orderDetailsModal, editOrderModal, cancelOrderConfirmModal;
    
    const orderDetailsElement = document.getElementById('orderDetailsModal');
    const editOrderElement = document.getElementById('editUserOrderModal');
    const cancelOrderElement = document.getElementById('cancelOrderConfirmModal');
    
    console.log('查找模态框元素结果:');
    console.log('orderDetailsElement:', orderDetailsElement);
    console.log('editOrderElement:', editOrderElement);
    console.log('cancelOrderElement:', cancelOrderElement);
    
    if (orderDetailsElement) {
        orderDetailsModal = new bootstrap.Modal(orderDetailsElement);
        console.log('订单详情模态框初始化成功');
    } else {
        console.error('未找到订单详情模态框元素');
    }
    
    if (editOrderElement) {
        editOrderModal = new bootstrap.Modal(editOrderElement);
        console.log('编辑订单模态框初始化成功');
    } else {
        console.error('未找到编辑订单模态框元素');
    }
    
    if (cancelOrderElement) {
        cancelOrderConfirmModal = new bootstrap.Modal(cancelOrderElement);
        console.log('取消订单确认模态框初始化成功');
    } else {
        console.error('未找到取消订单确认模态框元素');
    }

    // Status mapping for display
    const DISPLAY_STATUS_MAP = {
        "PENDING": "待处理",
        "SHIPPED": "已发货",
        "PICKED_UP": "已揽收",
        "IN_TRANSIT": "运输中",
        "UNRECEIVED": "未签收",
        "DELIVERED": "已签收",
        "CANCELED": "已取消"
    };

    function getDisplayStatus(status) {
        return DISPLAY_STATUS_MAP[status] || status;
    }

    // 辅助函数：根据状态获取徽章颜色类
    function getStatusBadgeClass(status) {
        switch (status) {
            case 'PENDING': return 'bg-secondary';
            case 'SHIPPED': return 'bg-info';
            case 'PICKED_UP': return 'bg-info';
            case 'IN_TRANSIT': return 'bg-primary';
            case 'UNRECEIVED': return 'bg-warning';
            case 'DELIVERED': return 'bg-success';
            case 'CANCELED': return 'bg-danger';
            default: return 'bg-secondary';
        }
    }

    // 查看订单详情按钮点击事件
    const viewButtons = document.querySelectorAll('.view-details-btn');
    console.log('找到查看按钮数量:', viewButtons.length);
    viewButtons.forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault();
            const orderId = this.dataset.orderId;
            console.log('查看订单详情 - Order ID:', orderId);

            if (!orderDetailsModal) {
                console.error('订单详情模态框未初始化');
                alert('模态框初始化失败，请刷新页面重试。');
                return;
            }

            fetch(`/orders/details/${orderId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(order => {
                    document.getElementById('modalOrderNumber').textContent = order.orderNumber;
                    document.getElementById('modalSenderName').textContent = order.senderName;
                    document.getElementById('modalSenderPhone').textContent = order.senderPhone;
                    document.getElementById('modalSenderAddress').textContent = order.senderAddress;
                    document.getElementById('modalReceiverName').textContent = order.receiverName;
                    document.getElementById('modalReceiverPhone').textContent = order.receiverPhone;
                    document.getElementById('modalReceiverAddress').textContent = order.receiverAddress;
                    document.getElementById('modalPackageType').textContent = order.packageType;
                    document.getElementById('modalWeight').textContent = order.weight;
                    document.getElementById('modalVolume').textContent = order.volume;
                    document.getElementById('modalPrice').textContent = order.price;
                    document.getElementById('modalStatus').textContent = getDisplayStatus(order.status);
                    document.getElementById('modalStatus').className = 'badge ' + getStatusBadgeClass(order.status);
                    document.getElementById('modalCreatedAt').textContent = order.createdAt ? new Date(order.createdAt).toLocaleString() : '';
                    document.getElementById('modalUpdatedAt').textContent = order.updatedAt ? new Date(order.updatedAt).toLocaleString() : '';

                    console.log('正在显示订单详情模态框...');
                    orderDetailsModal.show();
                })
                .catch(error => {
                    console.error('Error fetching order details:', error);
                    alert('无法加载订单详情，请稍后再试。');
                });
        });
    });

    // 修改订单信息按钮点击事件
    const editButtons = document.querySelectorAll('.edit-order-btn');
    console.log('找到修改按钮数量:', editButtons.length);
    editButtons.forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault();
            const orderId = this.dataset.orderId;
            console.log('修改订单 - Order ID:', orderId);

            if (!editOrderModal) {
                console.error('编辑订单模态框未初始化');
                alert('模态框初始化失败，请刷新页面重试。');
                return;
            }

            fetch(`/orders/details/${orderId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(order => {
                    document.getElementById('editOrderId').value = order.id;
                    document.getElementById('editOrderNumber').value = order.orderNumber;
                    document.getElementById('editSenderName').value = order.senderName;
                    document.getElementById('editSenderPhone').value = order.senderPhone;
                    document.getElementById('editSenderAddress').value = order.senderAddress;
                    document.getElementById('editReceiverName').value = order.receiverName;
                    document.getElementById('editReceiverPhone').value = order.receiverPhone;
                    document.getElementById('editReceiverAddress').value = order.receiverAddress;
                    document.getElementById('editPackageType').value = order.packageType;
                    document.getElementById('editWeight').value = order.weight;
                    // 显示体积和价格信息（只读）
                    document.getElementById('editVolumeDisplay').textContent = order.volume ? order.volume + ' m³' : '由管理员计算';
                    document.getElementById('editPriceDisplay').textContent = order.price ? order.price + ' 元' : '由管理员计算';

                    console.log('正在显示编辑订单模态框...');
                    editOrderModal.show();
                })
                .catch(error => {
                    console.error('Error fetching order details for edit:', error);
                    alert('无法加载订单详情进行修改，请稍后再试。');
                });
        });
    });

    // 保存修改按钮点击事件
    const saveEditBtn = document.getElementById('saveEditBtn');
    if (saveEditBtn) {
        saveEditBtn.addEventListener('click', function() {
            const orderId = document.getElementById('editOrderId').value;
            const updatedOrder = {
                id: orderId,
                orderNumber: document.getElementById('editOrderNumber').value,
                senderName: document.getElementById('editSenderName').value,
                senderPhone: document.getElementById('editSenderPhone').value,
                senderAddress: document.getElementById('editSenderAddress').value,
                receiverName: document.getElementById('editReceiverName').value,
                receiverPhone: document.getElementById('editReceiverPhone').value,
                receiverAddress: document.getElementById('editReceiverAddress').value,
                packageType: document.getElementById('editPackageType').value,
                weight: parseFloat(document.getElementById('editWeight').value)
            };

            fetch('/orders/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    [csrfHeader]: csrfToken
                },
                body: JSON.stringify(updatedOrder)
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(errorData => {
                        throw new Error(errorData.message || '网络响应不正常');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data === true) {
                    alert('订单修改成功！');
                    location.reload();
                } else {
                    alert('订单修改失败！');
                }
            })
            .catch(error => {
                console.error('Error saving order changes:', error);
                alert('保存修改失败：' + error.message);
            });
        });
    }

    // 取消订单按钮点击事件
    document.querySelectorAll('.cancel-order-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault();
            const orderId = this.dataset.orderId;
            const orderNumber = button.closest('tr').querySelector('td:first-child').textContent;
            
            if (!cancelOrderConfirmModal) {
                console.error('取消订单确认模态框未初始化');
                alert('模态框初始化失败，请刷新页面重试。');
                return;
            }
            
            document.getElementById('cancelOrderNumber').textContent = orderNumber;

            console.log('正在显示取消订单确认模态框...');
            cancelOrderConfirmModal.show();

            // Set order ID to confirm button for later use
            document.getElementById('confirmCancelBtn').dataset.orderId = orderId;
        });
    });

    // 确认取消订单按钮点击事件
    const confirmCancelBtn = document.getElementById('confirmCancelBtn');
    if (confirmCancelBtn) {
        confirmCancelBtn.addEventListener('click', function() {
            const orderId = this.dataset.orderId;

            fetch(`/orders/cancel/${orderId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    [csrfHeader]: csrfToken
                }
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(errorData => {
                        throw new Error(errorData.message || '网络响应不正常');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    alert('订单取消成功！');
                    location.reload();
                } else {
                    alert('订单取消失败：' + (data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Error canceling order:', error);
                alert('取消订单失败：' + error.message);
            });
        });
    }
}); 